module CurrentUserHelper
	protected
  def authenticated?
    !user_state.nil?
  end

  def current_user
    if authenticated?
      user = User.find_by_username user_state.username

      if user.nil?
				message = "User #{user_state.username} not found."
        delete_user_state
        raise message
      end

      return user
    else
      return nil
    end
  end

  def user_state
    session[:user_state]
  end

  def store_user_state(user_state)
    unless user_state.respond_to?("username")
      raise ArgumentError, "'#{user_state.to_s}' is not a user state object."
    end

    session[:user_state] = user_state
  end

  def delete_user_state
    session[:user_state] = nil
  end

  UserState = Struct.new(:username)
  def self.build_user_state_object(username)
    UserState.new(username)
  end

	def authorize_admin
		user = current_user
		if user && user.has_role(Role::Roles::ADMIN)
			return true
		end

		flash[:error] = "You don't have permission to access that resource"
		redirect_to error_url()
		return false
	end
end
